<?php

namespace common\models;

use Yii;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%user}}".
 *
 * @property integer $id
 * @property string $user_no
 * @property string $cwx_userid
 * @property integer $company_id
 * @property string $cwx_position
 * @property string $cwx_name
 * @property integer $cwx_gender
 * @property string $cwx_mobile
 * @property string $cwx_email
 * @property string $cwx_avatar
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $status
 */
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_no'], 'required'],
            [['company_id', 'cwx_gender', 'created_at', 'updated_at', 'status'], 'integer'],
            [['user_no'], 'string', 'max' => 16],
            [['cwx_userid', 'cwx_avatar'], 'string', 'max' => 255],
            [['cwx_position', 'cwx_name', 'cwx_email'], 'string', 'max' => 30],
            [['cwx_mobile'], 'string', 'max' => 20],
            [['user_no'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'id',
            'user_no' => '用户序列号',
            'cwx_userid' => '企业微信userId',
            'company_id' => '单位ID',
            'cwx_position' => '企业微信职位',
            'cwx_name' => '企业微信名字',
            'cwx_gender' => '性别',
            'cwx_mobile' => '手机号',
            'cwx_email' => '邮件地址',
            'cwx_avatar' => '企业微信头像地址',
            'created_at' => '会员创建时间',
            'updated_at' => '会员信息更新时间',
            'status' => '状态',
        ];
    }

    public static function add($userInfo)
    {
        if($user_info_detail = Yii::$app->cwx->CWXUser->findUserDetailByUserTicket($userInfo['user_ticket']))
            $userInfo = array_merge($userInfo,$user_info_detail);
        else
        {
            echo '企业微信授权获取用户信息失败,(或者是非企业成员)';
            return false;
        }
        //转换键名（加前缀cwx_）
        $userInfoTrans = [];
        foreach ($userInfo as $k=>$v)
        {
            $userInfoTrans['cwx_'.$k] = $v;
        }
        $userInfoTrans['user_no'] =  date('ymdHms').str_pad(mt_rand(1,9999),4,'0',STR_PAD_LEFT);
        $userInfoTrans['created_at'] =  time();
        $userInfoTrans['updated_at'] =  time();

        //保存用户基本信息
        $user = new User();
        $user->attributes = $userInfoTrans;
        if(!$user->save())
        {
            echo '创建用户过程失败';
            return false;
        }

        //保存用户部门信息
        foreach ($userInfo['department'] as $v)
        {
            $userToDepartment = new UserToDepartment();
            $userToDepartment->user_id = $user->id;
            $userToDepartment->cwx_department = $v;
            $userToDepartment->save();
        }
        return $user;
    }
    /**
     * Finds an identity by the given ID.
     * @param string|int $id the ID to be looked for
     * @return IdentityInterface the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($id)
    {
        $user = User::findOne($id);
        return $user;
    }

    /**
     * Finds an identity by the given token.
     * @param mixed $token the token to be looked for
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return null;
    }

    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|int an ID that uniquely identifies a user identity.
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Returns a key that can be used to check the validity of a given identity ID.
     *
     * The key should be unique for each individual user, and should be persistent
     * so that it can be used to check the validity of the user identity.
     *
     * The space of such keys should be big enough to defeat potential identity attacks.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @return string a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     */
    public function getAuthKey()
    {
        return null;
    }

    /**
     * Validates the given auth key.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @param string $authKey the given auth key
     * @return bool whether the given auth key is valid.
     * @see getAuthKey()
     */
    public function validateAuthKey($authKey)
    {
        return false;
    }
}
